<template>

  <div class="app-container">
    <div>
      <el-form inline>
        <!-- 期数选择 -->
        <el-form-item label="期数" prop="settingDate">
          <el-date-picker
              style="width: 150px"
              v-model="formParams.settingDate"
              type="month"
              placeholder="选择年月"
              format="YYYY-MM"
              value-format="YYYY-MM"
              class="full-width"
          />
        </el-form-item>

        <!-- 客户名称（可搜索下拉框） -->
        <el-form-item label="客户名称" prop="clientId">
          <el-select
              v-model="formParams.clientId"
              filterable
              clearable
              reserve-keyword
              placeholder="搜索客户"
              class="full-width"
          >
            <el-option
                v-for="item in clientSelection"
                :key="item.traderid"
                :label="item.name"
                :value="item.traderid"
            />
          </el-select>
        </el-form-item>

        <!-- 纸张类型（可搜索下拉框） -->
        <el-form-item label="纸张类型" prop="paperType">
          <el-input
              size="small"
              v-model="formParams.paperType"
              placeholder="纸张类型"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleList" type="primary" class="add-btn">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button type="primary" @click="handleAdd" class="add-btn">
            <el-icon><Plus /></el-icon>新增
          </el-button>
          <el-button @click="handleCopy" type="primary" class="copy-btn">
            <el-icon><EditPen /></el-icon>复制
          </el-button>
          <!--      <el-button @click="handleSubmit" type="primary">提交</el-button>-->
          <!--      <el-button @click="handleExport" type="warning">导出</el-button>-->
        </el-form-item>
      </el-form>
    </div>
    <div class="center">
      <el-table ref="tableRef" :data="tableData" style="width: 100%" border height="100%" :header-cell-style="{background:'#eef1f6',color:'#606266'}"
                @selection-change="handleSelectionChange" @row-click="handleRowClick" v-loading="loading">
        <el-table-column type="selection" width="55"/>
        <el-table-column type="index" width="55" label="序号" align="center"/>
        <el-table-column v-for="item in columns" :key="item.prop" :property="item.prop" :label="item.label"
                         :width="item.width"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-icon @click.stop="handleEdit(scope.row)" style="color: #0a84ff">
              <Edit/>
            </el-icon>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-pagination style="float: right; margin-top: 10px;" v-model:current-page="currentPage"
                       v-model:page-size="pageSize" :page-sizes="[50, 100, 150, 200]"
                       layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                       @current-change="handleCurrentChange" background/>
      </div>
    </div>

    <el-dialog
        v-model="dialogVisible"
        :title="title"
        width="600px"
        @closed="resetForm"
    >
      <el-form
          :model="formData"
          :rules="rules"
          ref="formRef"
          label-width="120px"
          label-position="left"
          class="custom-form"
      >
        <!-- 期数选择 -->
        <el-form-item label="期数" prop="settingDate">
          <el-date-picker
              v-model="formData.settingDate"
              type="month"
              placeholder="选择年月"
              format="YYYY-MM"
              value-format="YYYY-MM"
              class="full-width"
          />
        </el-form-item>

        <!-- 客户名称（可搜索下拉框） -->
        <el-form-item label="客户名称" prop="clientId">
          <el-select
              v-model="formData.clientId"
              filterable
              reserve-keyword
              placeholder="搜索客户"
              class="full-width"
          >
            <el-option
                v-for="item in clientSelection"
                :key="item.traderid"
                :label="item.name"
                :value="item.traderid"
            />
          </el-select>
        </el-form-item>

        <!-- 纸张类型（可搜索下拉框） -->
        <el-form-item label="纸张类型" prop="paperType">
          <el-input
              v-model="formData.paperType"
              class="full-width"
              placeholder="纸张类型"></el-input>
        </el-form-item>

        <!-- 返点单价（带单位数字输入） -->
        <el-form-item label="返点单价" prop="unitPrice">
          <el-input-number
              v-model="formData.unitPrice"
              :min="0"
              :precision="2"
              :step="0.1"
              controls-position="right"
              class="price-input"
          />
          <span class="unit">元/吨</span>
        </el-form-item>

<!--        &lt;!&ndash; 结算单位（可搜索下拉框） &ndash;&gt;-->
<!--        <el-form-item label="结算单位" prop="unitOfAccount">-->
<!--          <el-select-->
<!--              v-model="formData.unitOfAccount"-->
<!--              filterable-->
<!--              placeholder="结算单位"-->
<!--              class="full-width"-->
<!--          >-->
<!--            <el-option-->
<!--                v-for="item in clientSelection"-->
<!--                :key="item.traderid"-->
<!--                :label="item.name"-->
<!--                :value="item.traderid"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {ref, reactive, onMounted, computed} from "vue";
import request from '../../utils/request'
import {useLoading} from '../../utils/loading'
import {ElMessage, ElNotification} from 'element-plus'


import {useStore} from "vuex";

const store = useStore()
const username = computed(() => store.state.auth.user)

const tableData = ref()
const loading = ref(false)
// 表单数据
const formData = ref({
  settingDate: '',
  clientId: '',
  paperType: '',
  unitPrice: 0,
  unitOfAccount: ''
})

// 表单引用
const formRef = ref(null)

// 对话框可见性
const dialogVisible = ref(false)


// 重置表单
const resetForm = () => {
  // if (formRef.value) {
  //   formRef.value.resetFields()
  // }
}
// 表单验证规则
const rules = reactive({
  settingDate: [
    {required: true, message: '请选择期数', trigger: 'blur'}
  ],
  clientId: [
    {required: true, message: '请选择客户名称', trigger: 'blur'}
  ],
  paperType: [
    {required: true, message: '请输入纸张类型', trigger: 'blur'}
  ],
  unitPrice: [
    {required: true, message: '请输入返点单价', trigger: 'blur'},
    {type: 'number', min: 0, message: '单价不能为负数', trigger: 'blur'}
  ],
  unitOfAccount: [
    {required: true, message: '请选择结算单位', trigger: 'blur'}
  ]
})

const url = {
  listUrl: '/salesRebateSetting/list',
  querySelectionUrl: '/salesRebateSetting/querySelection',
  querySettingDateUrl: '/salesRebateSetting/querySettingDate',
  submitUrl: '/salesRebateSetting/submit',
  copyUrl: '/salesRebateSetting/copy',
}


const columns = [{
  prop: 'settingDate',
  label: '期数'
}, {
  prop: 'clientName',
  label: '客户名称'
}, {
  prop: 'paperType',
  label: '纸张类型'
}, {
  prop: 'unitPrice',
  label: '返利单价'
}]

const title = ref('新增')

const handleEdit = (row) => {
  title.value = '编辑'
  formData.value = JSON.parse(JSON.stringify(row))
  dialogVisible.value = true
}
const handleAdd = () => {
  title.value = '新增'
  formData.value = {
    settingDate: '',
    clientId: '',
    paperType: '',
    unitPrice: 0,
    unitOfAccount: ''
  }
  dialogVisible.value = true
}


// 生命周期钩子：组件挂载时获取数据
onMounted(async () => {
  tableHeight.value = window.innerHeight - 300

  handleList()
  httpQuerySelection()

})


const clientSelection = ref(null);
const goodsSelection = ref(null);
const httpQuerySelection = () => {
  request({
    url: url.querySelectionUrl,
    method: 'get'
  }).then(response => {
    goodsSelection.value = response.data.goodsSelection
    clientSelection.value = response.data.clientSelection
  }).catch(err => {
    console.log('err', err)
  }).finally(() => {
  })
}
// 分页
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(50)
const handleSizeChange = (val: number) => {
  handleList()
}
const handleCurrentChange = (val: number) => {
  handleList()
}

// 多选
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
const tableRef = ref();
const handleRowClick = (row) => {
  tableRef.value.toggleRowSelection(row); // 切换当前行选中状态
};


const tableHeight = ref(0);
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const loading = useLoading()
      request({
        url: url.submitUrl,
        method: 'post',
        params: {
          username: username.value,
        },
        data: formData.value
      }).then(res => {
        if (res.code == 200) {
          dialogVisible.value = false
          ElNotification.success({title: '成功提示', message: '提交成功'})
          handleList()
          return
        }
        ElNotification.error({title: '错误提示', message: res.message})
      }).catch(err => {
        ElNotification.error({title: '错误提示', message: err.message})
      }).finally(() => {
        loading.close()
      })
    } else {
      ElMessage.warning('请填写完整的表单信息')
    }
  })
}

const handleCopy = () => {
  if (!formParams.value.settingDate) {
    ElNotification.warning({
      title: '提示',
      message: '请选择期数'
    })
    return;
  }
  if (multipleSelection.value.length <= 0) {
    ElNotification.warning({
      title: '提示',
      message: '请选择记录'
    })
    return;
  }
  const index = multipleSelection.value.findIndex(item => item.settingDate === formParams.value.settingDate);
  if (index >= 0) {
    ElNotification.warning({
      title: '提示',
      message: '请把期数换成你需要的期数进行复制'
    })
    return
  }
  const loading = useLoading()
  request({
    url: url.copyUrl,
    method: 'post',
    data: multipleSelection.value,
    params: {
      settingDate: formParams.value.settingDate,
      username: username.value
    }
  }).then(res => {
    if (res.code == 200) {
      ElNotification.success({
        title: '提示',
        message: '复制成功'
      })
      handleList()
      return
    }
    ElNotification.warning({
      title: '错误提示',
      message: res.message
    })
  }).finally(() => {
    loading.close()
  })
}

const formParams = ref({})
const handleList = async () => {
  try {

    loading.value = true
    request({
      url: url.listUrl,
      method: 'get',
      params: {
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        ...formParams.value
      }
    }).then(response => {
      tableData.value = response.data
      total.value = response.total
    }).finally(() => {
      loading.value = false
    })
  } catch (error) {
    console.log('error', error)
  }
}

</script>

<style scoped>
.container {
  padding: 20px;
}

.add-btn {
  background: linear-gradient(135deg, #409eff, #79bbff);
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-size: 16px;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}
.copy-btn {
  background: linear-gradient(135deg, #71714a, #eeb936);
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-size: 16px;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}

.copy-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}

.custom-form {
  padding: 20px 30px;
  border-radius: 12px;
  background: #f8fafc;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.full-width {
  width: 100%;
}

.price-input {
  width: 180px;
  margin-right: 10px;
}

.unit {
  color: #606266;
  font-size: 14px;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #344758;
}

:deep(.el-input__inner) {
  border-radius: 8px;
  height: 33px;
  line-height: 33px;
}

:deep(.el-select .el-input__inner) {
  cursor: pointer;
}

.el-popper {
  border-radius: 8px !important;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1) !important;
}

.el-select-dropdown__item {
  padding: 10px 20px !important;
  font-size: 14px;
}

.el-select-dropdown__item:hover {
  background-color: #f5f7fa !important;
}

.el-date-picker {
  border-radius: 8px !important;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1) !important;
}

.el-dialog {
  border-radius: 12px !important;
  overflow: hidden;
}

.el-dialog__header {
  background: linear-gradient(135deg, #409eff, #79bbff);
  margin: 0 !important;
  padding: 16px 20px !important;
}

.el-dialog__title {
  color: white !important;
  font-weight: 600;
}

.el-dialog__headerbtn .el-dialog__close {
  color: white !important;
}

.center {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.app-container {
  padding: 0px;
  height: calc(100vh - 164px);
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}
</style>
